package com.example.casper.Experiment2024;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.core.graphics.Insets;
import androidx.core.os.EnvironmentCompat;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;

import com.example.casper.Experiment2024.data.TravelRecord;

import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class TravelRecordDetailsActivity extends AppCompatActivity {


    private static final int PICK_IMAGE_REQUEST = 1;
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 100;
    private EditText textPositionName;
    private EditText textRecordContent;
    private EditText editTextLatitude, editTextLongitude;
    // 用于显示照片的ImageView（无论是选择本地图片还是拍照后的图片）
    private ImageView imageView;
    private Uri imageUri;

    private FusedLocationProviderClient fusedLocationProviderClient;
    private double currentLatitude = 0;
    private double currentLongitude = 0;


    private static final String[] NEEDED_PERMISSIONS = new String[]{
            android.Manifest.permission.CAMERA,
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
            android.Manifest.permission.READ_EXTERNAL_STORAGE,
            android.Manifest.permission.ACCESS_FINE_LOCATION,
            android.Manifest.permission.ACCESS_COARSE_LOCATION
    };

    // 请求权限的请求码
    private static final int ACTION_REQUEST_PERMISSIONS = 0x001;
    // 请求相机权限的请求码
    private static final int PERMISSION_CAMERA_REQUEST_CODE = 0x00000012;
    // 用于判断是否为Android 10及以上版本
    private final boolean isAndroidQ = Build.VERSION.SDK_INT >= 29;
    // 用于保存图片的文件路径，Android 10以下使用图片路径访问图片
    private String mCameraImagePath;
    // 用于保存拍照图片的uri
    private Uri mCameraUri;
    // 拍照的请求码
    private static final int CAMERA_REQUEST_CODE = 1;
    // 用于标记是否拍过照片
    private Boolean imagestate = false;


    // 统一的“照片”按钮




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_travel_record_details);

        // 初始化视图控件
        textPositionName = findViewById(R.id.edit_position_name);
        textRecordContent = findViewById(R.id.edit_content);
        imageView = findViewById(R.id.imageView);
        editTextLatitude = findViewById(R.id.editTextLatitude);
        editTextLongitude = findViewById(R.id.editTextLongitude);
        Button buttonFetchLocation = findViewById(R.id.buttonFetchLocation);
        Button buttonSave = findViewById(R.id.button_ok);
        Button buttonSelectImage = findViewById(R.id.button_photo);



        // 进行权限相关的初始化操作
        initPermissions();
        // 初始化 FusedLocationProviderClient
        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);


        Intent intent = this.getIntent();
        if (intent != null && intent.hasExtra("name")) {
            loadRecordFromIntent(intent);
        }

        // 图片选择功能
        buttonSelectImage.setOnClickListener(v -> openFileChooser());

        // 保存记录功能
        buttonSave.setOnClickListener(v -> saveRecord());
        // 获取当前位置功能
        buttonFetchLocation.setOnClickListener(v -> checkLocationPermissionsAndFetch());


        // 处理窗口内边距，确保界面在不同屏幕配置下正常显示
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

    }

    private void openFileChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "选择图片"), PICK_IMAGE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK && data != null && data.getData() != null) {
            imageUri = data.getData();
            imageView.setImageURI(imageUri);
        }
    }
    private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
    private void saveRecord() {
        try {
            String name = textPositionName.getText().toString().trim();
            String latitudeStr = editTextLatitude.getText().toString().trim();
            String longitudeStr = editTextLongitude.getText().toString().trim();
            String description = textRecordContent.getText().toString().trim();

            if (latitudeStr.isEmpty() || longitudeStr.isEmpty()) {
                showToast("位置未获取，请点击获取位置");
                return;
            }

            double latitude;
            double longitude;
            latitude = Double.parseDouble(latitudeStr);
            longitude = Double.parseDouble(longitudeStr);



            if (latitude < -90 || latitude > 90) {
                showToast("纬度范围必须在 -90 到 90 之间");
                return;
            }
            if (longitude < -180 || longitude > 180) {
                showToast("经度范围必须在 -180 到 180 之间");
                return;
            }
            String imagePath;
            if (imageUri != null) {
                imagePath = imageUri.toString();
            } else {
                imagePath = Uri.parse("android.resource://" + getPackageName() + "/" + R.drawable.jnu_zhuhai_icon).toString();
            }


            Intent resultIntent = new Intent();
            resultIntent.putExtra("position_name", name);
            resultIntent.putExtra("latitude", latitude);
            resultIntent.putExtra("longitude", longitude);
            resultIntent.putExtra("record_content", description);
            resultIntent.putExtra("image_path", imagePath);

            setResult(RESULT_OK, resultIntent);
            finish();
        } catch (NumberFormatException e) {
            showToast("保存时发生错误");
        }
    }

    private void loadRecordFromIntent(Intent intent) {
        // 将已有数据加载到界面
        textPositionName.setText(intent.getStringExtra("position_name"));
        editTextLongitude.setText(String.valueOf(intent.getDoubleExtra("longitude", 0)));
        editTextLatitude.setText(String.valueOf(intent.getDoubleExtra("latitude", 0)));
        textRecordContent.setText(intent.getStringExtra("record_content"));

        String imagePath = intent.getStringExtra("image_path");
        if (imagePath != null) {
            imageUri = Uri.parse(imagePath);
            if (imageUri != null) {
                imageView.setImageURI(imageUri);
            } else {
                imageView.setImageResource(R.drawable.jnu_zhuhai_icon); // 默认图片资源
            }
        }
    }
    private void checkLocationPermissionsAndFetch() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
        } else {
            fetchLocation();
        }
    }

    private void fetchLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        fusedLocationProviderClient.getLastLocation().addOnSuccessListener(location -> {
            if (location != null) {
                currentLatitude = location.getLatitude();
                currentLongitude = location.getLongitude();

                editTextLatitude.setText(String.valueOf(currentLatitude));
                editTextLongitude.setText(String.valueOf(currentLongitude));
                showToast("位置获取成功: 纬度 " + currentLatitude + ", 经度 " + currentLongitude);
            } else {
                showToast("未能获取位置，请确保设备的 GPS 已打开");
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                fetchLocation();
            } else {
                showToast("未授予位置权限");
            }
        }
    }







    private void initPermissions() {
        if (!checkPermissions()) {
            ActivityCompat.requestPermissions(this, NEEDED_PERMISSIONS, ACTION_REQUEST_PERMISSIONS);
        } else {
            // 权限已授予，无需额外操作，因为后续点击“照片”按钮时会再检查具体操作相关权限
        }
    }


    private boolean checkPermissions() {
        if (NEEDED_PERMISSIONS == null || NEEDED_PERMISSIONS.length == 0) {
            return true;
        }
        boolean allGranted = true;
        for (String neededPermission : NEEDED_PERMISSIONS) {
            allGranted &= ContextCompat.checkSelfPermission(this, neededPermission) == PackageManager.PERMISSION_GRANTED;
        }
        return allGranted;
    }


    private void showPhotoOptionsDialog() {
        final String[] options = {"本地图片选择", "相机拍摄"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择照片来源");
        builder.setItems(options, (dialog, which) -> {
            switch (which) {
                case 0:
                    chooseLocalPhoto();
                    break;
                case 1:
                    checkPermissionAndCamera();
                    break;
            }
        });
        builder.show();
    }

    private void chooseLocalPhoto() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, 0x201);
    }


    private void checkPermissionAndCamera() {
        int hasCameraPermission = ContextCompat.checkSelfPermission(this,
                android.Manifest.permission.CAMERA);
        if (hasCameraPermission == PackageManager.PERMISSION_GRANTED) {
            openCamera();
        } else {
            // 没有权限，申请权限。
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
                    PERMISSION_CAMERA_REQUEST_CODE);
            Toast.makeText(this, "需要授予相机权限才能拍照哦", Toast.LENGTH_SHORT).show();
        }
    }


    @SuppressLint("QueryPermissionsNeeded")
    private void openCamera() {
        Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 判断是否有相机
        if (captureIntent.resolveActivity(this.getPackageManager())!= null) {
            File photoFile = null;
            Uri photoUri = null;
            if (isAndroidQ) {
                // 适配android 10
                photoUri = createImageUri();
            } else {
                // 10以下
                try {
                    photoFile = createImageFile();
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(this, "创建图片文件失败，请稍后再试", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (photoFile!= null) {
                    mCameraImagePath = photoFile.getAbsolutePath();
                    // 适配Android 7.0文件权限，通过FileProvider创建一个content类型的Uri
                    photoUri = FileProvider.getUriForFile(this, this.getPackageName() + ".fileprovider", photoFile);
                }
            }
            mCameraUri = photoUri;
            if (photoUri!= null) {
                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                startActivityForResult(captureIntent, CAMERA_REQUEST_CODE);
            }
        }
    }

    private Uri createImageUri() {
        String status = Environment.getExternalStorageState();
        // 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            return this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
        } else {
            return this.getContentResolver().insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, new ContentValues());
        }
    }


    private File createImageFile() throws IOException {
        String imageName = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        File storageDir = this.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        assert storageDir!= null;
        if (!storageDir.exists()) {
            storageDir.mkdir();
        }
        File tempFile = new File(storageDir, imageName);
        if (!Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(tempFile))) {
            return null;
        }
        return tempFile;
    }



}
